package com.sakura.oj.service;

import com.sakura.oj.constant.CommonConstant;
import com.sakura.oj.model.properties.AuthProperties;
import com.sakura.oj.model.vo.LoginUserVO;
import com.sakura.oj.utils.RedisUtil;
import com.sakura.oj.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * token服务
 */
@Service
@Slf4j
public class TokenService {

    @Resource
    private AuthProperties authProperties;

    /**
     * 创建token
     *
     * @param loginUserVO 登录成功的用户
     * @return token
     */
    public String createToken(LoginUserVO loginUserVO) {
        // 生成token
        String accessToken = TokenUtil.createToken(loginUserVO);
        // 存储到redis 1 token映射用户登录信息， 2, 用户id映射token
        RedisUtil.setCacheObject(CommonConstant.AUTH_TOKEN_KEY + accessToken, loginUserVO, authProperties.getTime(), authProperties.getUnit());
        RedisUtil.setCacheObject(CommonConstant.AUTH_USER_KEY + loginUserVO.getId(), accessToken, authProperties.getTime(), authProperties.getUnit());
        return accessToken;
    }
}
